#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：BroadviewCoss
@File    ：single_user_login.py.py
@IDE     ：PyCharm
@Author  ：kdly
@Date    ：2025/4/26 下午7:43
'''
import hashlib

from django_redis import get_redis_connection
from jwt import ExpiredSignatureError
from rest_framework_jwt.settings import api_settings


class SingleLogin:
    """
    单用户登录逻辑
    @param username: 用户名
    return
    """

    def __init__(self, username):
        self.username = username
        self.__redis_conn = self.__get_conn()
        self.__md5_username = self.__get_username()

    def __get_exp(self, token):
        try:
            jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
            res = jwt_decode_handler(token)
            return int(res.get('exp'))
        except ExpiredSignatureError:
            return 30000

    def __get_conn(self):
        """获取Redis连接"""
        return get_redis_connection("default")

    def __get_username(self):
        md5 = hashlib.md5()
        md5.update(self.username.encode('utf-8'))
        return md5.hexdigest()

    def set_redis_user_token(self, token):
        """
        redis设置键值对 username:token
        @param token: token
        """
        exp = self.__get_exp(token)
        # 设置带过期时间（单位：秒）
        self.__redis_conn.setex(self.__md5_username, exp, token)

    def set_black_list(self):
        """设置token黑名单"""
        black_list = self.__redis_conn.get(self.__md5_username + 'deny')
        black_list_value = ''
        if black_list:
            black_list_value = black_list.decode('utf-8')  # 转换为字符串
        token = self.__redis_conn.get(self.__md5_username)
        if token:
            token_decoded_value = token.decode('utf-8')  # 转换为字符串
            exp = self.__get_exp(token_decoded_value)
            self.__redis_conn.setex(self.__md5_username + 'deny', exp, token_decoded_value + "," + black_list_value)

    def get_black_list(self, token):
        """
        获取token黑名单
        @param token: token
        """
        # 获取单个键的值（返回字节类型，需解码）
        res = self.__redis_conn.get(self.__md5_username + 'deny')
        if res:
            decoded_value = res.decode('utf-8')  # 转换为字符串
            black_list = decoded_value.split(',')
            if token in black_list:
                return True
